// 是否授权，通过jwt实现

const { getResBody, getReqParams, getReqToken, consoleLog } = require("../../utils");

module.exports = secret => {
  return async function isAuth(ctx, next) {
    const token = getReqToken(ctx);
    if (!token) {
      ctx.status = 401;
      ctx.body = getResBody({ msg: "token未携带" });
      return;
    }
    try {
      const decodeToken = ctx.app.jwt.verify(token, secret); // 解析token
      await next();
    } catch (err) {
      const { name, message } = err;
      if (name === "JsonWebTokenError" || name === "TokenExpiredError") {
        ctx.status = 401;
        ctx.body = getResBody({ msg: "token已过期" });
      } else {
        consoleLog(`错误拦截：`, "danger", err);
        ctx.status = 500;
        ctx.body = getResBody({ msg: "服务器异常" });
      }
    }
  };
};
